﻿#_*_encoding:utf-8_*_
import os
import sys
import time
import datetime
import traceback
# import smtplib
from basic.myPublic import MySwitch
import basic.myGlobal as myGlobal
import requests
from basic.mySysCommon import MySysCommon
import configparser
import qrcode
from PIL import Image
import random
from basic.webTestCase import WebTestCase
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
# from automagica import *
from urllib.parse import urlparse



logger = myGlobal.getLogger()


class MyRequest(WebTestCase):
    u"""requests接口"""
    def __init__(self, myFileDispose, confPathName, logPathName):
        super(MyRequest, self).__init__()
        self.maxNumberTimes = 3  # 网络出错最大重试次数
        # self.tn = None
        self.url = ""

        self.myFileDispose = myFileDispose
        self.logPathName = logPathName
        self.confPathName = confPathName

        self.mySysCommon = MySysCommon()



        self.__getConfig()
        pass


    def __del__(self):
        # self.tn.close()
        pass


    def myMain(self, logPathName):
        """主"""
        self.mySysClearHistoryLog(self.logPathName)

        self.setUp()

        driver = self.driverWeb
        result = self.myLogin(driver)

        self.tearDown()


    def myJmeterHttpTest(self, dom, hashTree, method, protocol, domain, port, path, contentEncoding, idnum):
        """HTTP请求"""
        logger.debug("method:{} protocol:{} domain:{} port:{} path:{} contentEncoding:{} idnum:{}".format(method, protocol, domain, port, path, contentEncoding, idnum))
        httpSamplerProxy = self.mySysXmlCreateElement(dom, hashTree, 'HTTPSamplerProxy')
        self.mySysXmlCreateAttribute(httpSamplerProxy, "guiclass", "HttpTestSampleGui")
        self.mySysXmlCreateAttribute(httpSamplerProxy, "testclass", "HTTPSamplerProxy")
        if protocol == "":
            wenhaoNum = path.find("?")
            if wenhaoNum != -1:
                xiegangNum = path.rfind("/")
                if xiegangNum != -1:
                    self.mySysXmlCreateAttribute(httpSamplerProxy, "testname", "HTTP-{}-{}".format(idnum, path[xiegangNum+1:]))
                else:
                    self.mySysXmlCreateAttribute(httpSamplerProxy, "testname", "HTTP-{}-{}".format(idnum, path))
            else:
                self.mySysXmlCreateAttribute(httpSamplerProxy, "testname", "HTTP-{}-{}".format(idnum, path))
        else:
            self.mySysXmlCreateAttribute(httpSamplerProxy, "testname", "HTTP-{}-{}://{}:{}{}".format(idnum, protocol, domain, port, path))
        self.mySysXmlCreateAttribute(httpSamplerProxy, "enabled", "true")

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.domain")
        self.mySysXmlCreateTextNode(dom, stringProp, domain)

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.port")
        self.mySysXmlCreateTextNode(dom, stringProp, port)

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.protocol")
        self.mySysXmlCreateTextNode(dom, stringProp, protocol)

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.contentEncoding")
        self.mySysXmlCreateTextNode(dom, stringProp, contentEncoding)

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.path")
        self.mySysXmlCreateTextNode(dom, stringProp, path)

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.method")
        self.mySysXmlCreateTextNode(dom, stringProp, method)

        boolProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'boolProp')
        self.mySysXmlCreateAttribute(boolProp, "name", "HTTPSampler.follow_redirects")
        self.mySysXmlCreateTextNode(dom, boolProp, "true")

        boolProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'boolProp')
        self.mySysXmlCreateAttribute(boolProp, "name", "HTTPSampler.auto_redirects")
        self.mySysXmlCreateTextNode(dom, boolProp, "false")

        boolProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'boolProp')
        self.mySysXmlCreateAttribute(boolProp, "name", "HTTPSampler.use_keepalive")
        self.mySysXmlCreateTextNode(dom, boolProp, "true")

        boolProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'boolProp')
        self.mySysXmlCreateAttribute(boolProp, "name", "HTTPSampler.DO_MULTIPART_POST")
        self.mySysXmlCreateTextNode(dom, boolProp, "false")

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.embedded_url_re")

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.connect_timeout")

        stringProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'stringProp')
        self.mySysXmlCreateAttribute(stringProp, "name", "HTTPSampler.response_timeout")

        self.mySysXmlCreateElement(dom, hashTree, 'hashTree')

        return httpSamplerProxy


    def myJmeterHTTPArgument(self, dom, httpSamplerProxy, httpBody=None):
        """HTTP消息体"""
        logger.debug("httpBody:{}".format(str(httpBody)))
        boolProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'boolProp')
        self.mySysXmlCreateAttribute(boolProp, "name", "HTTPSampler.postBodyRaw")
        self.mySysXmlCreateTextNode(dom, boolProp, "true")

        elementProp = self.mySysXmlCreateElement(dom, httpSamplerProxy, 'elementProp')
        self.mySysXmlCreateAttribute(elementProp, "name", "HTTPsampler.Arguments")
        self.mySysXmlCreateAttribute(elementProp, "elementType", "Arguments")

        collectionProp = self.mySysXmlCreateElement(dom, elementProp, 'collectionProp')
        self.mySysXmlCreateAttribute(collectionProp, "name", "Arguments.arguments")

        if httpBody is not None:
            elementProp = self.mySysXmlCreateElement(dom, collectionProp, 'elementProp')
            self.mySysXmlCreateAttribute(elementProp, "name", "")
            self.mySysXmlCreateAttribute(elementProp, "elementType", "HTTPArgument")

            boolProp = self.mySysXmlCreateElement(dom, elementProp, 'boolProp')
            self.mySysXmlCreateAttribute(boolProp, "name", "HTTPArgument.always_encode")
            self.mySysXmlCreateTextNode(dom, boolProp, "false")

            stringProp = self.mySysXmlCreateElement(dom, elementProp, 'stringProp')
            self.mySysXmlCreateAttribute(stringProp, "name", "Argument.value")
            self.mySysXmlCreateTextNode(dom, stringProp, str(httpBody))

            stringProp = self.mySysXmlCreateElement(dom, elementProp, 'stringProp')
            self.mySysXmlCreateAttribute(stringProp, "name", "Argument.metadata")
            self.mySysXmlCreateTextNode(dom, stringProp, "=")


    def webLoginComm(self, driver):
        """大登录"""
        driver.get(self.url)
        driver.maximize_window()  # 最大化窗口

        # userName = "jianghaiyang"
        # password = "jianghaiyang"
        # self.myWtSendKeysWebEx(driver, By.XPATH, "//input[contains(@placeholder, '请输入账号')]", userName)
        # self.myWtSendKeysWebEx(driver, By.XPATH, "//input[contains(@placeholder, '请输入密码')]", password)
        # self.myWtClickEx(driver, By.XPATH, "//span[text()='登录']")


    def myLogin(self, driver):
        """登录"""
        try:
            self.webLoginComm(driver)

            while 1 == 1:
                if input("\n任意键开始录制(输入e退出软件)：") == "e":
                    break
                else:
                    handles = driver.window_handles
                    if len(handles) > 0:
                        driver.switch_to.window(handles[-1])
                        # logger.debug("当前录制的窗口名称：【{}】".format(driver.title))
                    else:
                        return None

                    driver.get_log('performance')

                input("\n录制中...(任意键结束录制)：")

                handles = driver.window_handles
                if len(handles) > 0:
                    driver.switch_to.window(handles[-1])
                else:
                    return None

                localList = self.myWtPerformanceNetworkLog(driver, 0, 0, excludeList=[])
                logger.debug(localList)

                if localList is not None:
                    self.myDispose(driver, localList)

            return True
        except:
            logger.error(traceback.format_exc())
            return None


    def myDispose(self, driver, localList):
        """处理"""
        demoFilename = "{}demo.jmx".format(self.confPathName)
        filename = "testInterface.jmx"
        self.mySysCopyFile(demoFilename, filename)

        hashTreeJ = None
        hashTreeF = None
        hashTreeO = None
        dom, root = self.mySysXmlReadFile(filename)
        hashTree1List = root.getElementsByTagName("hashTree")  # 获取所有关于movie节点下的标签内容
        for hashTree1 in hashTree1List:
            hashTree2List = hashTree1.getElementsByTagName('hashTree')
            for hashTree2 in hashTree2List:
                hashTree3List = hashTree2.getElementsByTagName('hashTree')
                num = 0
                for hashTree3 in hashTree3List:
                    hashTree4List = hashTree3.getElementsByTagName('hashTree')
                    logger.debug(hashTree4List)
                    for hashTree4 in hashTree4List:
                        if num == 2:
                            hashTreeJ = hashTree4
                            logger.debug(hashTreeJ)
                        elif num == 5:
                            hashTreeF = hashTree4
                            logger.debug(hashTreeF)
                        elif num == 7:
                            hashTreeO = hashTree4
                            logger.debug(hashTreeO)
                        num = num + 1
                    break
                break
            break

        currentUrl = driver.current_url
        anlyse = urlparse(currentUrl)
        baseDomain = anlyse.hostname
        basePort = anlyse.port
        if basePort is None:
            if "https:" in currentUrl.lower():
                basePort = "443"
            else:
                basePort = "80"
        logger.debug("{}:{}".format(baseDomain, basePort))

        urlList = []
        httpBodyList = []
        contentEncoding = "UTF-8"
        idnum = 1
        for local in localList:
            # logger.debug(local)
            localBody = localList.get(local)
            # logger.debug(localBody)
            url = localBody.get("url")
            logger.debug(url)
            if "://" not in url:
                continue
            urlsp = str(url).split("://")
            protocol = urlsp[0]
            # logger.debug(urlsp[1])
            domain = ""
            port = "80"
            path = ""
            # 检查是否有端口信息
            if ":" in urlsp[1]:
                tmp = urlsp[1].split(":")
                domain = tmp[0]
                # logger.debug(tmp[1])
                num = tmp[1].find("/")
                port = tmp[1][0:num]
                path = tmp[1][num:]
            else:
                num = urlsp[1].find("/")
                domain = urlsp[1][0:num]
                path = urlsp[1][num:]
                if protocol.lower() == "https":
                    port = "443"

            logger.debug(protocol)
            logger.debug(domain)
            logger.debug(port)
            logger.debug(path)

            httpBody = localBody.get("request_postData")
            method = localBody.get("method")
            if method is None:
                method = "GET"
            request_headers = localBody.get("request_headers")

            if self.checkSame(url, urlList, httpBody, httpBodyList) is False:
                logger.debug("重复接口：{}\n{}".format(url, httpBody))
                continue
            urlList.append(url)
            httpBodyList.append(httpBody)

            if hashTreeJ is not None and hashTreeF is not None and hashTreeO is not None:
                # if (baseDomain != domain or basePort != port) or url[-1] == "/":
                # if baseDomain != domain or url[-1] == "/":
                if (baseDomain != domain and basePort != port) or url[-1] == "/":
                    logger.debug("其它接口：{}".format(url))
                    httpSamplerProxy = self.myJmeterHttpTest(dom, hashTreeO, method, protocol, domain, port, path, contentEncoding, idnum)
                    self.myJmeterHTTPArgument(dom, httpSamplerProxy, httpBody)
                    idnum = idnum + 1
                elif "." in path:
                    # httpSamplerProxy = self.myJmeterHttpTest(dom, hashTreeF, method, protocol, domain, port, path, contentEncoding, idnum)
                    httpSamplerProxy = self.myJmeterHttpTest(dom, hashTreeF, method, "", "", "", path, "", idnum)
                    self.myJmeterHTTPArgument(dom, httpSamplerProxy, httpBody)
                    idnum = idnum + 1
                else:
                    # httpSamplerProxy = self.myJmeterHttpTest(dom, hashTreeJ, method, protocol, domain, port, path, contentEncoding, idnum)
                    httpSamplerProxy = self.myJmeterHttpTest(dom, hashTreeJ, method, "", "", "", path, "", idnum)
                    self.myJmeterHTTPArgument(dom, httpSamplerProxy, httpBody)
                    idnum = idnum + 1

                # self.mySysXmlWriteFile(dom, filename)
        self.mySysXmlWriteFile(dom, filename)


    def checkSame(self, preparingTmp, preparingList, parametersTmp, parametersList):
        for num in range(len(preparingList)):
            pre = preparingList[num]
            if preparingTmp == pre:
                if parametersTmp == parametersList[num]:
                    return False
        return True


    def __getConfig(self):
        fileName = '{}config.ini'.format(self.confPathName)

        cf = configparser.ConfigParser()
        cf.read(fileName, encoding="utf-8-sig")
        self.url = cf.get('WEB', 'url')


